package com.example.web.controller;

import com.example.web.annotation.RequiresPermission;
import com.example.web.entity.Menu;
import com.example.web.entity.MenuTree;
import com.example.web.entity.Result;
import com.example.web.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 菜单控制器
 */
@RestController
@RequestMapping("/api/system/menu")
@CrossOrigin(origins = "http://localhost:3001", allowCredentials = "true")
public class MenuController {

    @Autowired
    private MenuService menuService;

    /**
     * 获取菜单列表
     */
    @GetMapping("/list")
    @RequiresPermission("system:menu:list")
    public Result<List<Menu>> list() {
        List<Menu> menus = menuService.getAllMenus();
        return Result.success(menus);
    }

    /**
     * 获取菜单树
     */
    @GetMapping("/tree")
    @RequiresPermission("system:menu:list")
    public Result<List<MenuTree>> tree() {
        List<MenuTree> menuTree = menuService.getMenuTree();
        return Result.success(menuTree);
    }

    /**
     * 根据角色ID获取菜单树
     */
    @GetMapping("/tree/{roleId}")
    @RequiresPermission("system:menu:list")
    public Result<List<MenuTree>> treeByRoleId(@PathVariable Long roleId) {
        List<MenuTree> menuTree = menuService.getMenuTreeByRoleId(roleId);
        return Result.success(menuTree);
    }

    /**
     * 获取菜单详情
     */
    @GetMapping("/{id}")
    @RequiresPermission("system:menu:query")
    public Result<Menu> getInfo(@PathVariable Long id) {
        Menu menu = menuService.getMenuById(id);
        return Result.success(menu);
    }

    /**
     * 新增菜单
     */
    @PostMapping
    @RequiresPermission("system:menu:add")
    public Result<Void> add(@RequestBody Menu menu) {
        int rows = menuService.addMenu(menu);
        return rows > 0 ? Result.success() : Result.error("新增菜单失败");
    }

    /**
     * 修改菜单
     */
    @PutMapping
    @RequiresPermission("system:menu:edit")
    public Result<Void> update(@RequestBody Menu menu) {
        int rows = menuService.updateMenu(menu);
        return rows > 0 ? Result.success() : Result.error("修改菜单失败");
    }

    /**
     * 删除菜单
     */
    @DeleteMapping("/{id}")
    @RequiresPermission("system:menu:remove")
    public Result<Void> remove(@PathVariable Long id) {
        int rows = menuService.deleteMenuById(id);
        return rows > 0 ? Result.success() : Result.error("删除菜单失败");
    }

    /**
     * 批量删除菜单
     */
    @DeleteMapping("/batch/{ids}")
    @RequiresPermission("system:menu:remove")
    public Result<Void> batchRemove(@PathVariable Long[] ids) {
        int rows = menuService.deleteMenuByIds(ids);
        return rows > 0 ? Result.success() : Result.error("批量删除菜单失败");
    }
}